#include "sqleditor.h"
#include "ui_sqleditor.h"
#include <QDebug>

SqlEditor::SqlEditor(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SqlEditor)
{
    ui->setupUi(this);
}

SqlEditor::~SqlEditor()
{
    delete ui;
}

void SqlEditor::setDatabaseInfo(const DatabaseInfo &dbInfo)
{
    m_dbInfo = dbInfo;
}

void SqlEditor::setSqlText(const QString &sql)
{
    ui->textEdit->setText(sql);
    m_sql = sql;
}

QString SqlEditor::sqlText()
{
    m_sql = ui->textEdit->textCursor().selectedText();
    if(m_sql.isEmpty())
        m_sql = ui->textEdit->toPlainText();
    return m_sql;
}

void SqlEditor::runSql()
{
    MysqlDB db(m_dbInfo.connName);
    db.setDatabaseInfo(m_dbInfo);
    QSqlRecord record ;
    QVector<QVariant> data;
    db.sqlData(m_sql, record, data);
//    qInfo() << record << data;
    if(data.size() <= 0)
        return;
    ui->tabWidget->setCurrentIndex(1);
    ui->tableWidget->setColumnCount(record.count());
    QStringList head;
    for(int i = 0; i < record.count(); i++)
    {
        head << record.fieldName(i);
    }
    ui->tableWidget->setHorizontalHeaderLabels(head);
    int rowCount = data.size() / record.count();
    ui->tableWidget->setRowCount(rowCount);
    for(int i = 0; i < data.size(); i++)
    {
        int row = i / record.count();
        for(int j = 0; j < record.count(); j++)
        {
            if(QVariant::Int == record.field(j).type())
            {
                QTableWidgetItem *item = ui->tableWidget->item(row, j);
                if(Q_NULLPTR == item)
                {
                    item = new QTableWidgetItem;
                    ui->tableWidget->setItem(row, j, item);
                }
                item->setText(QString::number(data.at(i).toInt()));
            }
            else if(QVariant::String == record.field(j).type())
            {
                QTableWidgetItem *item = ui->tableWidget->item(row, j);
                if(Q_NULLPTR == item)
                {
                    item = new QTableWidgetItem;
                    ui->tableWidget->setItem(row, j, item);
                }
                item->setText(data.at(i).toString());
            }
        }
    }
}
